package com.cmict.data.framework.security.core.util;


import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

@Slf4j
public class RSAUtils {
    /**
     * 加密算法RSA
     */
    public static final String ALGORITHM = "RSA";

    /** key值大小 */
    private static int KEYSIZE = 1024;

    /**
     * 生成密钥对
     */
    private static void generateKeyPair() throws Exception {
        SecureRandom sr = new SecureRandom(); //RSA算法可信任的随机数源
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM); //RSA算法创建KeyPairGenerator对象
        kpg.initialize(KEYSIZE, sr); //随机数据源初始化KeyPairGenerator对象
        KeyPair kp = kpg.generateKeyPair(); //生成密匙对
        Key publicKey = kp.getPublic(); //得到公钥
        Key privateKey = kp.getPrivate(); //得到私钥
        System.out.println(publicKey.getFormat());
        System.out.println(privateKey.getFormat());
    }

    /**
     * 加密方法
     * @param source 源数据
     * @return
     */
    public static String encrypt(String source) throws Exception {
        String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCngww2227VYWvHogm7dtTdA8wORn2opOmLrwZorThC2wEE2+ZifkO/tfQmjMTHe6Caj5sicZH+CIuhQomA6u9R/gGO4ueXwXfpEQqPw2j8+Jlnv0cYhOte4GXwYIKlaakxwAjG/6xJIRzYo72Lpstq/6o0W22c6/gxSidArqLp5QIDAQAB";
        byte[] publicKeyBy = Base64.getDecoder().decode(publicKeyStr.getBytes());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyBy));
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        // 获得加密的byte[]
        byte[] encryptByte = cipher.doFinal(source.toString().getBytes("UTF-8"));
        // 转变成字符串以进行传输
        String strKey = Base64.getEncoder().encodeToString(encryptByte);
        return strKey;
    }

    /**
     * 解密算法
     * @param cryptograph
     * @return
     * @throws Exception
     */
    public static String decrypt(String cryptograph){
        try{
            String privateKeyStr = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKeDDDbbbtVha8eiCbt21N0DzA5Gfaik6YuvBmitOELbAQTb5mJ+Q7+19CaMxMd7oJqPmyJxkf4Ii6FCiYDq71H+AY7i55fBd+kRCo/DaPz4mWe/RxiE617gZfBggqVpqTHACMb/rEkhHNijvYumy2r/qjRbbZzr+DFKJ0CuounlAgMBAAECgYBCWn60HCfDDlwLL/x67Y9UHPTvkqyj6O86DZKUVEk88lNtAU45JZrgjcqwmoI4IphzoP7qneIepnPo5Npi3qz9QI6kQRAlKIPmhSI2ZfuBjw4iQApsfbI8YJolyXm45ca1flW7TJHOOuCQQoy5hFp/UJ7Yt2awh/ye/uD9D/r7AQJBAOYuNQcImMtyhHFdebrloZtcHnOeN1hWwiOYAg/NQ+GprEyu+slCbXAaEdWnLEQQK8wxiCj4AW1SceLBUIAR+UkCQQC6TUS4FxrNiizqsaB7/XvruAb3b/RsGZnyx7bl+XCu5SO7+iqLA0XU/zIQx5mEdP+BbvS3AGBrMIa51sqzBee9AkBWzCvQ2CwN48QPn6kMkhTrqcQN4yaJmEWi+GomnUewq7O+QulsxTDRafM5ts1ZaSOq3y6yDDs1hzZMxIrfkGeJAkEAkrqIhPSth3RsK+v6Ga1rDBvEYN0sBHelaDEjO71ZomWV31cIarQJK9hR9iU+I7SCB877raX+Sm3NrlAdFSJxgQJBAJsvg1+z0rMaCuEa7fnmjoHJ0abW4X5uXIy6dydo+0Y/5vbDOLEBWvo8brTNmjGjbZa+mRvtN3XLdlenKkrjRfw=";
            byte[] privateKeyBy = Base64.getDecoder().decode(privateKeyStr.getBytes());
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBy));
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            // 进行解密
            byte[] decryptByte = cipher.doFinal(Base64.getDecoder().decode(cryptograph));
            // 转换成字符串
            String receiveMsg = new String(decryptByte, "UTF-8");
            return receiveMsg;
        }catch (Exception e){
            log.error(e.toString());
        }
        return "";
    }

}
